package com.xinqi.modules.discuss.assistant.service.impl;

import com.alibaba.fastjson2.JSON;
import com.xinqi.common.base.enums.YesNoNumberEnum;
import com.xinqi.common.base.response.R;
import com.xinqi.common.core.enums.*;
import com.xinqi.modules.chat.chat.official.dto.req.ChatAssistantContentCreateDTO;
import com.xinqi.modules.chat.chat.official.dto.req.ChatAssistantContentMainDTO;
import com.xinqi.modules.chat.chat.official.dto.req.ChatAssistantContentTotalDTO;
import com.xinqi.modules.chat.chat.official.dto.req.ChatAssistantContentUpdateDTO;
import com.xinqi.modules.chat.chat.official.json.BaseMessage;
import com.xinqi.modules.chat.chat.official.json.NoticeMessage;
import com.xinqi.modules.chat.chat.official.json.VideoMessage;
import com.xinqi.modules.course.clazz.client.ClassStudentClient;
import com.xinqi.modules.course.clazz.dto.rsp.ClassStudentResultDTO;
import com.xinqi.modules.discuss.assistant.AssistantListen;
import com.xinqi.modules.discuss.assistant.convert.AssistantConvert;
import com.xinqi.modules.discuss.assistant.service.AssistantNoticeService;
import com.xinqi.modules.discuss.notice.domain.CourseNoticeEntity;
import com.xinqi.modules.discuss.notice.domain.CourseNoticeStudentLogEntity;
import com.xinqi.modules.discuss.notice.service.CourseNoticeService;
import com.xinqi.modules.stats.assistant.dto.rsp.AssistantTotalResultDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class AssistantNoticeServiceImpl implements AssistantNoticeService {

    @Lazy
    private final AssistantListen assistantListen;

    private final AssistantConvert assistantConvert;

    @Lazy
    private final ClassStudentClient classStudentClient;

    @Lazy
    private final CourseNoticeService courseNoticeService;

    /**
     * 公告发布消息体
     */
    @Override
    public List<ChatAssistantContentCreateDTO> sentAssistantNotice(Long contentId) {
        CourseNoticeEntity entity = courseNoticeService.getById(contentId);
        if (Objects.isNull(entity)) {
            return null;
        }
        List<ClassStudentResultDTO> students = this.getClassStudentList(entity);
        List<ChatAssistantContentCreateDTO> list = new ArrayList<>();

        ChatAssistantContentCreateDTO initCreate = assistantListen.initChatAssistantContent(AssistantMessageTypeEnum.NOTICE);

        NoticeMessage initMessage = initNoticeMessage(entity);

        students.forEach(item -> {
            ChatAssistantContentCreateDTO create = assistantConvert.create(initCreate);
            create.setContentId(entity.getId());
            create.setProgressState(checkProgressState(entity).getCode());

            NoticeMessage message = assistantConvert.create(initMessage);
            message.setClassRole(item.getClassRole());
            message.setParticipateNum(0);
            message.setNotParticipateNum(0);
            create.setMessageContext(JSON.toJSONString(message));
            create.setRecipient(item.getStudentId());
            create.setSubmittedState(checkSubmitState(entity, item,null).getCode());
            list.add(create);
        });
        return list;
    }

    /**
     * 根据作业类型获取要发送学生列表
     */
    private List<ClassStudentResultDTO> getClassStudentList(CourseNoticeEntity entity) {
        // 获取班级所有成员信息
        List<ClassStudentResultDTO> students = R.as(classStudentClient.allUserListByClassId(entity.getClassId()));
        // 获取老师以及关系用户信息
        return students.stream().filter(student -> Objects.equals(YesNoNumberEnum.YES.getCode(), student.getIsRelationalStudent())
            || Objects.equals(YesNoNumberEnum.YES.getCode(), student.getIsTeacher())).collect(Collectors.toList());
    }

    /**
     * 新奇助手初始化发布公告信息
     */
    private NoticeMessage initNoticeMessage(CourseNoticeEntity entity){
        // 初始化消息体
        BaseMessage base = assistantListen.initBaseMessage(entity.getClassId());
        NoticeMessage message = JSON.parseObject(JSON.toJSONString(base), NoticeMessage.class);
        message.setContentId(entity.getId());
        message.setTitle(entity.getTitle());
        if (Objects.nonNull(entity.getContent())) {
            message.setContent(entity.getContent());
        } else {
            message.setContent("[附件]");
        }
        message.setEndTime(entity.getEndTime());
        message.setIsConfirm(entity.getIsConfirm());
        // 默认学生未确认
        message.setIsStuConfirm(YesNoNumberEnum.NO.getCode());
        if (entity.getIsConfirm() == 1) {
            message.setRemark("需学生确认");
        }
        return message;
    }

    /**
     * 公告一键提醒息体
     */
    @Override
    public List<ChatAssistantContentCreateDTO> sentAssistantNoConfirmNotice(Long contentId, List<CourseNoticeStudentLogEntity> students) {
        List<ChatAssistantContentCreateDTO> list = new ArrayList<>();
        if (Objects.isNull(students) || students.size() == 0) {
            return list;
        }
        CourseNoticeEntity entity = courseNoticeService.getById(contentId);
        if (Objects.isNull(entity)) {
            return list;
        }

        List<Long> studentIds = students.stream().map(CourseNoticeStudentLogEntity::getStudentId).collect(Collectors.toList());
        List<ClassStudentResultDTO> studentList = R.as(classStudentClient.findClassRelationshipStudentList(entity.getClassId(), studentIds));

        ChatAssistantContentCreateDTO initCreate = assistantListen.initChatAssistantContent(AssistantMessageTypeEnum.NOTICE);
        NoticeMessage initMessage = initNoticeMessage(entity);
        studentList.forEach(item -> {
            ChatAssistantContentCreateDTO create = assistantConvert.create(initCreate);
            create.setType(AssistantTypeEnum.REMIND.getCode());
            create.setContentId(entity.getId());
            create.setProgressState(checkProgressState(entity).getCode());
            NoticeMessage message = assistantConvert.create(initMessage);
            message.setClassRole(item.getClassRole());
            message.setParticipateNum(0);
            message.setNotParticipateNum(0);
            create.setMessageContext(JSON.toJSONString(message));
            create.setRecipient(item.getStudentId());
            create.setSubmittedState(checkSubmitState(entity, item,null).getCode());
            list.add(create);
        });
        return list;
    }

    /**
     * 公告确认消息体
     */
    public List<ChatAssistantContentUpdateDTO> sentAssistantNoticeSure(Long contentId, Long studentId) {
        // 获取公告内容
        CourseNoticeEntity entity = courseNoticeService.getById(contentId);
        if (Objects.nonNull(entity)) {
            // 获取学生信息
            ClassStudentResultDTO student = R.as(classStudentClient.findByStudentId(entity.getClassId(), studentId));

            // 初始化公告确认消息体-集合
            List<ChatAssistantContentUpdateDTO> list = new ArrayList<>();

            // 创建学生公告确认-实体
            ChatAssistantContentUpdateDTO update = new ChatAssistantContentUpdateDTO();
            update.setMessageType(AssistantMessageTypeEnum.NOTICE.getType());
            update.setContentId(entity.getId());
            update.setRecipient(student.getStudentId());
            NoticeMessage message = initNoticeMessage(entity);
            message.setClassRole(student.getClassRole());
            message.setIsStuConfirm(YesNoNumberEnum.YES.getCode());
            update.setMessageContext(JSON.toJSONString(message));
            if (Objects.equals(CourseResourseStatusEnum.FINISHED.getCode(), entity.getStatus())) {
                update.setProgressState(AssistantStateEnum.ENDED.getCode());
            } else {
                update.setProgressState(AssistantStateEnum.PROGRESS.getCode());
            }
            update.setSubmittedState(checkSubmitState(entity, student, Integer.valueOf(YesNoNumberEnum.YES.getCode())).getCode());

            list.add(update);
            return list;
        } else {
            return null;
        }
    }

    /**
     * 判断公告进行中已结束公用方法
     */
    private AssistantStateEnum checkProgressState(CourseNoticeEntity entity) {
        return AssistantStateEnum.PROGRESS;
    }

    /**
     * 判断用户按钮显示状态
     * 说明：确认公告：老师、助教 按钮提示文字 查看详情；学生、课代表 按钮提示文字 未确认：去确认 确认：已确认
     *      非确认公告：老师、助教、课代表、学生  按钮提示文字 查看详情
     */
    private AssistantStateEnum checkSubmitState(CourseNoticeEntity notice, ClassStudentResultDTO student, Integer confirm) {
        if (Objects.equals(YesNoNumberEnum.NO.getCode(), notice.getIsConfirm())) {
            return AssistantStateEnum.VIEW_DETAIL;
        } else {
            if (Objects.equals(ClassRoleEnum.TEACHER, student.getClassRole()) ||
                Objects.equals(ClassRoleEnum.ASSISTANT, student.getClassRole())) {
                return AssistantStateEnum.VIEW_DETAIL;
            } else {
                if (Objects.nonNull(confirm)) {
                    if (Objects.equals(YesNoNumberEnum.YES.getCode(), confirm)) {
                        return AssistantStateEnum.CONFIRMED;
                    } else {
                        return AssistantStateEnum.UNCONFIRMED;
                    }
                } else {
                    return AssistantStateEnum.UNCONFIRMED;
                }
            }
        }

    }

    /**
     * 进行中的公告
     */
    public List<CourseNoticeEntity> noticeRunningList(Long classId) {
        return courseNoticeService.selectNoticeRunningList(classId);
    }

}
